package com.lixin.smartclassroom.ui.home.tab2.activity

import android.animation.Animator
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.drake.channel.receiveEvent
import com.drake.channel.sendEvent
import com.drake.net.utils.scopeNetLife
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.api.piyue
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.bean.EvaluationQuestionsDto
import com.lixin.smartclassroom.bean.PiYueDto
import com.lixin.smartclassroom.bean.ScoreDto
import com.lixin.smartclassroom.databinding.ActivityLookAnswerBinding
import com.lixin.smartclassroom.ext.user_role
import com.lixin.smartclassroom.ui.home.adapter.choiceMoreQuestionAnswer
import com.lixin.smartclassroom.ui.home.adapter.choiceQuestionAnswer
import com.lixin.smartclassroom.ui.home.adapter.imgList
import com.lixin.smartclassroom.ui.home.adapter.scoreList
import com.lixinkeji.base.BaseActivity
import com.lixinkeji.extension.dp2px
import com.lixinkeji.extension.getIntentInt
import com.lixinkeji.extension.getIntentSerializable
import com.lixinkeji.extension.getIntentString
import com.lixinkeji.extension.gone
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.setRoundRectBg
import com.lixinkeji.extension.toast
import com.lixinkeji.extension.visible
import per.goweii.anylayer.AnyLayer
import per.goweii.anylayer.Layer
import per.goweii.anylayer.ktx.doOnClickToDismiss
import per.goweii.anylayer.ktx.setContentAnimator
import per.goweii.anylayer.ktx.setSwipeDismiss
import per.goweii.anylayer.utils.AnimatorHelper
import per.goweii.anylayer.widget.SwipeLayout

/**
 * Description 查看答案
 * Author: lwc
 * Date:2023/12/9 17:19
 */
class LookAnswerAct : BaseActivity<ActivityLookAnswerBinding>() {
    override fun getViewBinding() = ActivityLookAnswerBinding.inflate(layoutInflater)

    override fun topBarHide() = true
    override fun startPadding() = false
    override fun title() = "查看答案"
    private lateinit var paperList: ArrayList<DataListBean>
    private lateinit var piyueList: ArrayList<PiYueDto>
    private var currentPosition = 0
    private var id = ""
    private var xiaojieid = ""
    private var fromType = ""


    override fun iniView() {
        currentPosition = getIntentInt("currentPosition")
        id = getIntentString("id")
        xiaojieid = getIntentString("xiaojieid")
        fromType = getIntentString("fromAct")
        paperList = getIntentSerializable("paperList")
        piyueList = ArrayList()
        for (i in 0 until paperList.size) {
            val scoreList = ArrayList<ScoreDto>()
            piyueList.add(PiYueDto(paperList[i].id!!, paperList[i].answer!!, paperList[i].type!!,scoreList))
        }
        binding.apply {
            tvQuestionType.setRoundRectBg(Color.parseColor("#4B6AEF"), dp2px(3f).toInt())
            setCurrentData(currentPosition)



            receiveEvent<ScoreDto>("tag_set_score_data") {
                for (i in 0 until piyueList[currentPosition].fenzhi?.size!!){
                    if(piyueList[currentPosition].fenzhi?.get(i)?.wid ==it.wid){
                        piyueList[currentPosition].fenzhi?.get(i)?.sourse = it.sourse
                        return@receiveEvent
                    }
                }
                piyueList[currentPosition].fenzhi?.add(it)
            }
        }

    }

    private fun setCurrentData(currentPosition: Int) {
        binding.apply {

            if (currentPosition == 0) {
                if (paperList.size != 1) {
                    btnPrevious.gone()
                    btnNext.visible()
                } else {
                    when (user_role) {
                        3 -> {
                            when (fromType) {
                                "4" -> {
                                    btnPrevious.gone()
                                    btnNext.visible()
                                    btnNext.text = "返回首页"
                                }

                                else -> {
                                    btnPrevious.gone()
                                    btnNext.visible()
                                    btnNext.text = "批阅完成"
                                }
                            }
                        }

                        else -> {
                            btnPrevious.gone()
                            btnNext.visible()
                            btnNext.text = "返回首页"
                        }
                    }


                }

            } else if (currentPosition + 1 == paperList.size) {
                when (user_role) {
                    3 -> {
                        when (fromType) {
                            "4" -> {
                                btnPrevious.visible()
                                btnNext.gone()
                            }

                            else -> {
                                btnPrevious.visible()
                                btnNext.visible()
                                btnNext.text = "批阅完成"
                            }
                        }
                    }

                    else -> {
                        btnPrevious.visible()
                        btnNext.gone()
                    }
                }

            } else {
                btnPrevious.visible()
                btnNext.visible()
                btnNext.text = "下一题"
            }

            tvQuestionNo.text = (currentPosition + 1).toString() + "/" + paperList.size

            when (paperList[currentPosition].type) {
                "1" -> {
                    val stringTitle =
                        "(" + paperList[currentPosition].nums + "分) " + paperList[currentPosition].title + "(" + paperList[currentPosition].answer + ")"
                    val spannableString = SpannableString(stringTitle)
//设置颜色
                    spannableString.setSpan(
                        ForegroundColorSpan(Color.parseColor("#009B93")),
                        spannableString.length - 3,
                        spannableString.length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    tvTitle.text = spannableString


                    tvQuestionType.text = "单选题"
                    rcvAnswer.visible()
                    llApplicationQuestions.gone()
                    llScore.gone()
                    imgRecycler.gone()
                    rcvAnswer.choiceQuestionAnswer(paperList[currentPosition].right!!).models =
                        paperList[currentPosition].options
                }

                "2" -> {
                    val stringTitle =
                        "(" + paperList[currentPosition].nums + "分) " + paperList[currentPosition].title + "(" + paperList[currentPosition].answer + ")"
                    val spannableString = SpannableString(stringTitle)
//设置颜色
                    spannableString.setSpan(
                        ForegroundColorSpan(Color.parseColor("#009B93")),
                        spannableString.length - paperList[currentPosition].answer?.length!! - 2,
                        spannableString.length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    tvTitle.text = spannableString



                    tvQuestionType.text = "多选题"
                    rcvAnswer.visible()
                    llApplicationQuestions.gone()
                    llScore.gone()
                    imgRecycler.gone()
                    rcvAnswer.choiceMoreQuestionAnswer(paperList[currentPosition].right!!).models =
                        paperList[currentPosition].options
                }

                "3" -> {
                    if (paperList[currentPosition].nums.isNullOrEmpty()) {
                        tvTitle.text =
                            paperList[currentPosition].title
                        tvQuestionType.text = "评价题"
                    } else {
                        tvTitle.text =
                            "(" + paperList[currentPosition].nums + "分) " + paperList[currentPosition].title
                        tvQuestionType.text = "主观题"
                    }

                    tvAnswer.text = paperList[currentPosition].answer
                    etScore.setText("")
                    if (paperList[currentPosition].answerimage?.isEmpty() == true) {
                        imgRecycler.gone()
                    } else {
                        imgRecycler.visible()
                        imgRecycler.imgList(2).models =
                            paperList[currentPosition].answerimage!!.split("|")

                    }

                    rcvAnswer.gone()
                    llApplicationQuestions.visible()
                    when (user_role) {
                        3 -> {
                            when (fromType) {
                                "4" -> llScore.gone()
                                else ->{
                                    llScore.visible()
                                    val evaluateQuestionAct = EvaluationQuestionsDto("测试维度",paperList[currentPosition].nums!!,weiduname="维度名称")
                                    val evaluateScoreList =  ArrayList<EvaluationQuestionsDto>()
                                    evaluateScoreList.add(evaluateQuestionAct)
                                    recyclerScore.scoreList().models = evaluateScoreList
                                }
                            }
                        }

                        else -> llScore.gone()
                    }

                }

                else -> {
                    tvTitle.text =
                        paperList[currentPosition].title
                    tvQuestionType.text = "评价题"
                    tvAnswer.text = paperList[currentPosition].answer
                    etScore.setText("")
                    if (paperList[currentPosition].answerimage?.isEmpty() == true) {
                        imgRecycler.gone()
                    } else {
                        imgRecycler.visible()
                        imgRecycler.imgList(2).models =
                            paperList[currentPosition].answerimage!!.split("|")
                    }

                    rcvAnswer.gone()
                    llApplicationQuestions.visible()
                    when (user_role) {
                        3 -> {
                            when (fromType) {
                                "4" -> {
                                    llScore.gone()
                                }
                                else -> {
                                    llScore.visible()
                                    val evaluateQuestionAct = EvaluationQuestionsDto("测试维度",paperList[currentPosition].nums!!,weiduname="维度名称")
                                    val evaluateScoreList =  ArrayList<EvaluationQuestionsDto>()
                                    evaluateScoreList.add(evaluateQuestionAct)
                                    recyclerScore.scoreList().models = evaluateScoreList
                                }
                            }
                        }

                        else -> llScore.gone()
                    }
                }

            }
        }

    }

    override fun onClick() {
        binding.apply {
            ivBack.onClick {
                finish()
            }
            tvAnalysis.onClick {

                AnyLayer.dialog(this@LookAnswerAct)
                    .contentView(R.layout.dialog_question_analysis)
                    .gravity(Gravity.BOTTOM)
                    .setSwipeDismiss(SwipeLayout.Direction.BOTTOM)
                    .setContentAnimator(object :
                        Layer.AnimatorCreator {
                        override fun createInAnimator(target: View): Animator {
                            return AnimatorHelper.createBottomInAnim(target)
                        }

                        override fun createOutAnimator(target: View): Animator {
                            return AnimatorHelper.createBottomOutAnim(target)
                        }

                    }).backgroundDimAmount(0.5f).bindData {
                        val imgAd = it.getView<ImageView>(R.id.imgAd)
                        val llAnswer = it.getView<LinearLayout>(R.id.llAnswer)
                        val tvRightAnswer = it.getView<TextView>(R.id.tvRightAnswer)
                        val tvAnalysis = it.getView<TextView>(R.id.tvAnalysis)
                        val btnNextDialog = it.getView<TextView>(R.id.btnNext)
                        val btnPreviousDialog = it.getView<TextView>(R.id.btnPrevious)
                        tvRightAnswer?.text = paperList[currentPosition].right
                        tvAnalysis?.text = "【解析】\n" + paperList[currentPosition].jiexi

                        when (paperList[currentPosition].type!!) {
                            "1", "2" -> {
                                llAnswer?.visible()
                                imgAd?.gone()
                            }

                            else -> {
                                llAnswer?.gone()
                                imgAd?.gone()
                            }
                        }
                        if (currentPosition == 0) {
                            if (paperList.size != 1) {
                                btnPreviousDialog?.gone()
                                btnNextDialog?.visible()
                            } else {
                                btnPreviousDialog?.gone()
                                btnNextDialog?.visible()
                                btnNextDialog?.text = "返回首页"
                            }
                        } else if (currentPosition + 1 == paperList.size) {
                            btnPreviousDialog?.gone()
                            btnNextDialog?.text = "上一题"
                        } else {
                            btnPreviousDialog?.visible()
                            btnNextDialog?.visible()
                            btnNextDialog?.text = "下一题"
                        }

                    }.doOnClickToDismiss(R.id.btnClose) { }.doOnClickToDismiss(R.id.btnPrevious) {
                        currentPosition--
                        setCurrentData(currentPosition)
                    }.doOnClickToDismiss(R.id.btnNext) {
                        if (currentPosition + 1 == paperList.size) {
                            when (user_role) {
                                3 -> {
                                    teacherPiYue()
                                }

                                else -> {
                                    finish()
                                }
                            }
                        } else {
                            currentPosition++
                            setCurrentData(currentPosition)
                        }
                    }.show()


            }
            btnNext.onClick {
                if (currentPosition + 1 == paperList.size) {
                    when (user_role) {
                        3 -> {
                            when (fromType) {
                                "4" -> {
                                    finish()
                                }

                                else -> teacherPiYue()
                            }

                        }

                        else -> {
                            finish()
                        }
                    }
                } else {
                    currentPosition++
                    setCurrentData(currentPosition)
                }
            }

            btnPrevious.onClick {
                currentPosition--
                setCurrentData(currentPosition)
            }


//            etScore.doAfterTextChanged {
//                if(it.toString().isNotEmpty()){
//                    if(!paperList[currentPosition].nums.isNullOrEmpty()){
//                        if (it.toString().toDouble() <= paperList[currentPosition].nums?.toDouble()!!)
//                            piyueList[currentPosition].fenzhi = it.toString()
//                        else{
//                            toast("评分不能超过最高分")
//                            etScore.setText("")
//                        }
//                    }else{
//                        toast("本题分值异常")
//                        etScore.setText("")
//                    }
//                }
//
//
//            }

        }
    }

    private fun teacherPiYue() {
        piyueList.forEach {
            if (it.type == "3" && it.fenzhi?.isEmpty() == true) {
                toast("有未批阅题目，请检查后再次提交")
                return
            }
        }
        scopeNetLife {
            piyue(id, piyueList, xiaojieid)
            sendEvent("cs", "refreshData")
            sendEvent("cs", "refreshButtonUI")
            finish()
        }

    }


}